package com.ytktt.study.week9.task3.rpcfx.server;

import com.ytktt.study.week9.task3.rpcfx.annotation.RpcfxServiceProvider;
import com.ytktt.study.week9.task3.rpcfx.constant.RpcfxConstant;
import com.ytktt.study.week9.task3.rpcfx.utils.StringFormatUtils;
import org.reflections.Reflections;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Set;

/**
 * RpcfxServiceProvider注解扫描器
 *
 * @author ytk
 */
public class RpcfxServiceProviderAutoConfigureRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Reflections refs = new Reflections(RpcfxConstant.SERVICE_PACKAGE_PREFIX);
        Set<Class<?>> rpcfxServiceClassSet = refs.getTypesAnnotatedWith(RpcfxServiceProvider.class);
        for (Class<?> clazz : rpcfxServiceClassSet) {
            RpcfxServiceProvider anno = clazz.getAnnotation(RpcfxServiceProvider.class);
            // 目前这样要求只能实现一个接口
            String serviceName = StringFormatUtils.lowerFirstLetter(clazz.getInterfaces()[0].getSimpleName());
            String beanName = StringFormatUtils.genRealServiceName(serviceName, anno.group(), anno.version());
            GenericBeanDefinition beanDef = new GenericBeanDefinition();
            beanDef.setBeanClass(clazz);
            registry.registerBeanDefinition(beanName, beanDef);
        }
    }
}
